package com.cmw.auntapp.ui;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cmw.auntapp.R;
import com.cmw.auntapp.component.ConfirmDialog;
import com.cmw.auntapp.component.OrderCancelDialog;
import com.cmw.auntapp.component.SwitchButton;
import com.cmw.auntapp.constant.CommandType;
import com.cmw.auntapp.constant.Constant;
import com.cmw.auntapp.core.base.vo.AppVersionResult;
import com.cmw.auntapp.core.base.vo.DataResult;
import com.cmw.auntapp.core.util.AppTools;
import com.cmw.auntapp.core.util.DateUtil;
import com.cmw.auntapp.core.util.StringHandler;
import com.cmw.auntapp.core.util.SystemUtil;
import com.cmw.auntapp.core.util.ToastAlert;
import com.cmw.auntapp.presenter.AuntPresenter;
import com.cmw.auntapp.presenter.MainPresenter;
import com.cmw.auntapp.presenter.MsgPresenter;
import com.cmw.auntapp.presenter.OrderPresenter;
import com.cmw.auntapp.service.LocationService;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import lombok.Data;
import okhttp3.Callback;

import static com.cmw.auntapp.R2.drawable.circle_home_three_active;
import static com.cmw.auntapp.R2.drawable.switch_track;
import static com.cmw.auntapp.constant.Constant.HANDLER_APK_DOWNLOAD_PROGRESS;
import static com.cmw.auntapp.constant.Constant.NO_AUTH;
import static com.cmw.auntapp.constant.Constant.NO_LOGIN;
import static com.cmw.auntapp.core.util.ToastAlert.ACTIONBTN_OK;

/**
 * 首页
 * @Auth chengmingwei
 * @date 2021-04-05 16:48
 */
public class MainActivity extends BaseActivity {

    //ll_msg_tip
    @BindView(R.id.ll_msg_tip)
    LinearLayout llMsgTip;

    @BindView(R.id.tv_grabbing_orders)
    TextView tvGrabbingOrders;

    @BindView(R.id.tv_doing_orders)
    TextView tvDoingOrders;

    @BindView(R.id.vw_defaultStatus)
    View vwDefaultStatus;

    @BindView(R.id.pb_orderStatus)
    View pbOrderStatus;

    @BindView(R.id.tv_msg_tip)
    TextView tvMsgTip;

    @BindView(R.id.btn_tip_auth)
    TextView btnTipAuth;

    @BindView(R.id.btn_work_status)
    SwitchButton btnWorkStatus;

    private ProgressDialog progressDialog;

    private boolean grabbingOrderDoing = false;

    private static final long TIMEOUT_MILLS = 10 * 1000L; //30秒定时获取一下待抢订单

    private MainPresenter mainPresenter;

    private AuntPresenter auntPresenter;

    private OrderPresenter orderPresenter;

    private Integer currOrderCount = 0; // 订单数量

    private boolean isWorkStatus = false; // 是否在岗 (true:在岗, false:离岗)

    OrderCancelDialog.Builder dialogBuilder = null;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            int what = msg.what;
            switch (what) {
                case 9999 :{
                    if (!grabbingOrderDoing) {
                        return;
                    }
                    long startTime = msg.getData().getLong("startTime");
                    updateGrabbingTime(startTime);
                    sendRoundTime(what, startTime);
                    break;
                } case HANDLER_APK_DOWNLOAD_PROGRESS: {
                    Log.i(TAG,"what = "+msg.what + ", progress = "+ msg.arg1);
                    progressDialog.setProgress(msg.arg1);
                    //progressDialog.incrementProgressBy(msg.arg1);
                    break;
                }
            }
        }
    };


    @Override
    protected int getActivityLayout() {
        return R.layout.activity_main;
    }

    
    @Override
    void onInit(Bundle savedInstanceState) {
        setTitle(R.string.home_title, false);
        AssetManager assets = getAssets();
        Typeface fromAsset = Typeface.createFromAsset(assets, "fonts/dfbudingw12_gb.ttf");
        tvGrabbingOrders.setTypeface(fromAsset);
        tvDoingOrders.setTypeface(fromAsset);
        ToastAlert.init(this);
        mainPresenter = new MainPresenter(this);
        auntPresenter = new AuntPresenter(this);
        orderPresenter = new OrderPresenter(this);
        btnWorkStatus.setOnToggleListener(toggle -> doSetWorkStatu());
        checkPermissionRequest();
        //grabbingOrder(null);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume...");
        reset();
        loadData();
    }

    private void reset() {
        grabbingOrderDoing = false;
        cancelOrder(null);
    }

    /**
     * App检测更新
     */
    private void checkUpdate() {
        mainPresenter.checkUpdate();
    }

    /**
     * 安装新APP
     * @param appVersionResult
     */
    private void confirmInstallApk(final AppVersionResult appVersionResult){
        String oldVersionNum = AppTools.getVersionCode(this)+"";
        String versionNum = appVersionResult.getVersionNum();
        String upContent = appVersionResult.getUpcontent();
        String content = String.format("%s。\n 确定将当前APP由 %s 版本升级到 %s 版本吗？", upContent,oldVersionNum, versionNum);
        ToastAlert.confirm(this,"App更新提示",content,new ToastAlert.DialogCallback(){
            @Override
            public void execute(String actionBtn) {
                if(!actionBtn.equals(ACTIONBTN_OK)) return;
                showProgressDialog(appVersionResult);
                mainPresenter.downloadAPK(appVersionResult, handler);
            }
        });
    }

    private void showProgressDialog(AppVersionResult appVersionResult){
        String versionNum = appVersionResult.getVersionNum();
        String title = String.format("V%s.0 App 安装包下载", versionNum);
        String content = String.format("正在下载最新V%s.0版App，请稍后...", versionNum);
        progressDialog =  new ProgressDialog(MainActivity.this);//实例化ProgressDialog
        progressDialog.setMax(100);//设置最大值
        progressDialog.setTitle(title);//设置标题
        progressDialog.setIcon(R.mipmap.ic_launcher);//设置标题小图标
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//设置样式为横向显示进度的样式
        progressDialog.setMessage(content);
        progressDialog.incrementProgressBy(0);//设置初始值为0，其实可以不用设置，默认就是0
        progressDialog.setIndeterminate(false);//是否精确显示对话框，flase为是，反之为否
        //添加确定按钮
        //参数1 设置按钮样式
        //参数2，设置按钮文本
        //参数3，设置按钮监听事件
        progressDialog.setButton(DialogInterface.BUTTON_POSITIVE,"确定",new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(MainActivity.this,"确认下载完毕！",Toast.LENGTH_SHORT).show();
            }
        });


        //是否可以通过返回按钮退出对话框
        progressDialog.setCancelable(true);
        progressDialog.show();//显示对话框
    }

    /**
     * 更新抢单时间
     * @param startTime 开始时间
     */
    private void updateGrabbingTime(long startTime) {
        long currTime = System.currentTimeMillis();
        long seconds = (currTime - startTime)/1000;
        Log.i(TAG, "startTime = "+startTime+", seconds = "+seconds);
        long minutes = seconds / 60;
        long currSeconds = seconds - (minutes * 60);
        String currMinutes = "00";
        if (minutes < 10) {
            currMinutes = "0"+minutes;
        } else {
            currMinutes = ""+minutes;
        }
        String currSecondsStr = "00";
        if (currSeconds < 10) {
            currSecondsStr = "0"+currSeconds;
        } else {
            currSecondsStr = ""+currSeconds;
        }
        String currTimeStr = String.format("%s:%s", currMinutes, currSecondsStr);
        String txt = getResources().getText(R.string.home_tip_doing_orders).toString();
        txt = String.format(txt+"%s", currTimeStr);
        tvDoingOrders.setText(txt);
    }

    /**
     * 定时轮询进行分：秒计数
     * @param what
     * @param startTime
     */
    private void sendRoundTime(int what, long startTime) {
        Message newMsg = new Message();
        newMsg.what = what;
        Bundle data = new Bundle();
        data.putLong("startTime", startTime);
        newMsg.setData(data);
        handler.sendMessageDelayed(newMsg, 1000);
    }


    /**
     * 离/在岗切换
     */
    public void doSetWorkStatu(){
        boolean flag = btnWorkStatus.isToggle();
        if (flag) { // 离岗
            if(grabbingOrderDoing) {
                ToastAlert.showMsg("您当前正处在在抢单状态，不能切换为离岗状态。");
                btnWorkStatus.setToggle(false);
                return;
            }
            isWorkStatus = false;
            auntPresenter.unWork();
        } else { // 在岗
            isWorkStatus = true;
            auntPresenter.onWork();
        }
    }


    /**
     * 我的 -> 跳转到用户中心
     */
    @OnClick(R.id.iv_my_center)
    public void doGoUserCenter(View view){
        boolean isLogin = mainPresenter.isLogin();
        if (!isLogin) {
            go(LoginActivity.class);
            return;
        }
        Constant.userCenterBackActivity = this.getClass();
        go(UserCenterActivity.class);
    }

    private void loadData() {
        boolean isLogin = mainPresenter.isLogin();
        if (!isLogin) {
            tvMsgTip.setText(R.string.home_text_no_login);
            btnTipAuth.setText(R.string.home_btn_login);
            btnTipAuth.setTag(NO_LOGIN);
            btnTipAuth.setVisibility(View.VISIBLE);
            return;
        }
        boolean isRealAuth = mainPresenter.isRealAuth();
        if (!isRealAuth) {
            tvMsgTip.setText(R.string.home_text_no_auth);
            btnTipAuth.setText(R.string.home_btn_auth);
            btnTipAuth.setTag(NO_AUTH);
            btnTipAuth.setVisibility(View.VISIBLE);
            showMakeSureDialog();
            return;
        }
        mainPresenter.getOrderCount();
        checkUpdate();
    }

    private void showMakeSureDialog() {
        ConfirmDialog dialog = new ConfirmDialog();
        dialog.setConfirmBtnTxt(getString(R.string.home_btn_go_auth))
                .setContent(getString(R.string.home_text_no_auth));
        dialog.setDialogClickListener(new ConfirmDialog.onDialogClickListener() {
            @Override
            public void onSureClick() {
                goAuth(null);
            }
            @Override
            public void onCancelClick() { //这里是取消操作

            }
        });
        dialog.show(getSupportFragmentManager(), "");
    }


    public void checkPermissionRequest() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(Manifest.permission.ACCESS_FINE_LOCATION).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                Log.e(TAG, "定位权限申请："+(aBoolean ? "成功" : "失败"));
                // 启动定位服务
                getApplicationContext().startService(new Intent(MainActivity.this, LocationService.class));
            }
        });
    }

    public void confirmInstallApp(final AppVersionResult appVersionResult) {
        RxPermissions permissions = new RxPermissions(this);
        permissions.setLogging(true);
        permissions.request(Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                Log.e(TAG, "外部存储权限申请："+(aBoolean ? "成功" : "失败"));
                confirmInstallApk(appVersionResult);
            }
        });
    }

    /**
     * 每1分钟自动获取阿姨待抢订单
     */
    public void scheduleTimeout(){
        handler.postDelayed(() -> {
            Log.i(TAG, "scheduleTimeout,time:"+ DateUtil.dateFormatToStr(DateUtil.DATE_TIME_FORMAT2, new Date()));
            mainPresenter.getOrderCount();
        }, TIMEOUT_MILLS);
    }

    public void cancel(){
        if (null == handler) return;
        handler.removeCallbacksAndMessages(null);
    }

    /**
     * 去认证或登录按钮
     */
    @OnClick(R.id.btn_tip_auth)
    public void goAuth(View view){
        Integer authTag = (Integer) btnTipAuth.getTag();
        if (null == authTag) {
            Log.e(TAG,"按钮的 tag 属性值为空！");
            return;
        }
        if (authTag.intValue() == NO_LOGIN) { // 未登录
            go(LoginActivity.class);
            return;
        }
        if (authTag.intValue() == NO_AUTH) { // 未实名
            go(UserEditActivity.class);
            return;
        }
        Log.e(TAG,"按钮的 tag 属性值无法识别，无法进行下一步跳转动作！");
    }

    /**
     * 抢单
     * @param view
     */
    public void grabbingOrder(View view) {

//        Map<String, String> params = new HashMap<>();
//        params.put("orderId", "12");
//        go(OrderReceiveActivity.class, params); //跳转到接单页面
//        if (1 == 1) return;
        if (!isWorkStatus) {
            ToastAlert.showMsg("您当前是离岗状态不能抢单!");
            return;
        }

        if (currOrderCount.intValue() <= 0) {
            ToastAlert.showMsg("暂无订单可抢!");
            return;
        }

        Log.w(TAG,"grabbingOrder . 已经开始抢单...");
        tvGrabbingOrders.setVisibility(View.INVISIBLE);
        tvDoingOrders.setVisibility(View.VISIBLE);
        pbOrderStatus.setVisibility(View.VISIBLE);
        vwDefaultStatus.setVisibility(View.INVISIBLE);
        orderPresenter.grabbing();  // 抢单
        Message msg = new Message();
        Bundle data = new Bundle();
        data.putLong("startTime", new Date().getTime());
        msg.setData(data);
        msg.what = 9999; // 代表抢单
        handler.sendMessageDelayed(msg, 1000);
        grabbingOrderDoing = true;
    }

    /**
     * 点正在抢单弹出取消订单提示
     * @param view
     */
    public void cancelOrder(View view) {
        Log.w(TAG,"cancelOrder . 取消订单...");
        tvGrabbingOrders.setVisibility(View.VISIBLE);
        tvDoingOrders.setVisibility(View.INVISIBLE);
        vwDefaultStatus.setVisibility(View.VISIBLE);
        pbOrderStatus.setVisibility(View.GONE);
        String txt = getResources().getText(R.string.home_tip_doing_orders).toString();
        txt = String.format(txt+"%s", "00:00");
        tvDoingOrders.setText(txt);
        grabbingOrderDoing = false;
    }

    private void showOrderTip(Integer orderCount) {
        int txtResId = R.string.home_text_no_orders;
        int txtColor = Color.BLACK;
        int llBackgroudResId = R.drawable.title_home_tip;
        if (orderCount != null && orderCount.intValue() > 0) { //有新订单
            txtResId = R.string.home_text_have_orders;
            txtColor = Color.WHITE;
            llBackgroudResId = R.drawable.title_home_tip_active;
        }
        tvMsgTip.setText(txtResId);
        tvMsgTip.setTextColor(txtColor);
        llMsgTip.setBackgroundResource(llBackgroudResId);
        btnTipAuth.setVisibility(View.GONE);
    }

    private void setGrabbingBtn() {
        int backgroudResId = R.drawable.circle_home_three;
        int textColor = R.color.colorCCGray;
        if (currOrderCount > 0) {
            textColor = R.color.black33;
            backgroudResId = circle_home_three_active;
        }
        tvGrabbingOrders.setTextColor(getColor(textColor));
        vwDefaultStatus.setBackgroundResource(backgroudResId);
    }

    @Override
    protected boolean doFailure(CommandType commandType, DataResult dataResult) {
        switch (commandType) {
            case GET:{ //当前阿姨订单数量
                scheduleTimeout();
                break;
            }
            case PUT:{ // 在/离岗切换失败
                btnWorkStatus.setToggle(isWorkStatus);
                break;
            }case GRABBING: { // 抢单
                //grabbingOrderDoing = false; //停止计时
                cancelOrder(null);
                break;
            }
        }
        return true;
    }

    @Override
    protected boolean doSuccess(CommandType commandType, DataResult dataResult) {
        switch (commandType) {
            case CHECK_APP_UPDATE:{ // APP 安装
                AppVersionResult appVersionResult = dataResult.getData(AppVersionResult.class);
                confirmInstallApp(appVersionResult);
                //confirmInstallApp(appVersionResult);
                break;
            } case GET:{ //当前阿姨订单数量
                 Integer orderCount = (Integer)dataResult.getDatas();
                this.currOrderCount = orderCount;
                showOrderTip(orderCount);
                setGrabbingBtn();
                scheduleTimeout();
                break;
            } case GRABBING:{ // 抢单
                ToastAlert.showMsg("您已成功抢到新订单!");
                String orderId = (String)dataResult.getDatas();
                Map<String, String> params = new HashMap<>();
                params.put("orderId", orderId);
                go(OrderReceiveActivity.class, params); //跳转到接单页面
                grabbingOrderDoing = false;
                break;
            } case PUT:{ //离/在岗切换
                String msg = null;
                if(isWorkStatus){
                    msg = "您当前是\"在岗状态\"，可以开始抢单!";
                } else {
                    msg = "您当前是\"离岗状态\"，不允许抢单!";
                }
                ToastAlert.showMsg(msg);
                break;
            }
        }
        return true;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onDestroy() {
        cancel();
        super.onDestroy();
    }
}
